package 破坏单例模式以及解决;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

public class Client {
    private static final String PATH="C:\\Users\\zhq\\Desktop\\result.txt";

    public static void main(String[] args)  throws Exception{
//        writeToFile();
//        调用两次后发现两个对象的地址不同那么说明破坏了单例模式
//        readFromFile();
//        readFromFile();

        // 在加了readResolve方法之后发现返回的两个对象的内存地址是相同的，此时解决了序列化和反序列化破坏单例模式的问题


        Singleton3 singleton=Singleton3.getInstance();
        System.out.println(singleton);

        Class<Singleton3> clazz = Singleton3.class;
        Constructor<Singleton3> declaredConstructor = clazz.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        Singleton3 singleton3 = declaredConstructor.newInstance();
        System.out.println(singleton3);

    }

    public static void readFromFile() throws Exception {
        ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream(PATH));

//        因为在readObject()方法中会去判断是否定义了这个readResolve方法，如果有直接返回这个对象
        Singleton3 object =(Singleton3) objectInputStream.readObject();
        System.out.println(object);

        objectInputStream.close();


    }

    //
    public  static void writeToFile() throws Exception{
        Singleton3 singleton3=Singleton3.getInstance();
        ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream(PATH));
        objectOutputStream.writeObject(singleton3);
        objectOutputStream.close();
    }
}
